package com.betterjr.common.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.betterjr.common.utils.UserUtils;

public class RuleChangeHandlerInterceptor implements HandlerInterceptor {

    private static final String RULELIST_ROLE_CONSTANT = "ruleListRole_Constant";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (containErrorRequestUri(request)) {

            String ruleList = request.getParameter(RULELIST_ROLE_CONSTANT);
            // System.out.println(request.getRequestURI());
            if (StringUtils.isNoneBlank(ruleList)) {
                // 进行更换企业角色
                ParameterHttpRequestWrapper requestWrapper = new ParameterHttpRequestWrapper(request);
                // System.out.println(request.getRequestURI() + "......" + ruleList);
                if (!UserUtils.isEqureList(ruleList, UserUtils.findInnerRules())) {

                    UserUtils.setRuleList(ruleList);
                }
                // 移除某个参数
                requestWrapper.removeParameter(RULELIST_ROLE_CONSTANT);
            }
            return true;
        } else {
            return false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

    }

    private boolean containErrorRequestUri(HttpServletRequest request) {

        if (FilterSpecialURIChain.filterURIFlag(request.getRequestURI())) {
            return false;
        }

        return true;

    }

}
